package jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;

/**
 * 实现用户注册功能
 * 程序启动后, 要求用户输入用户名,密码,昵称,年龄
 * 将输入的信息保存到userinfo表中完成注册
 */
public class RegUser {
    public static void main(String[] args) {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection connection = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/tedu?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true",
                    "root",
                    "root"
            );
            System.out.println("与数据库连接成功");
            Statement statement = connection.createStatement();
            //接收用户输入
//            Scanner sc = new Scanner(System.in);
//            System.out.println("请输入用户名");
//            String username = sc.nextLine();
//            System.out.println("请输入密码");
//            String pwd = sc.nextLine();
//            System.out.println("请输入昵称");
//            String nickname = sc.nextLine();
//            System.out.println("请输入年龄(0~120)");
//            String age = sc.nextLine();
            UserInfo userInfo = InputUtil.getInputObject(new UserInfo(),"欢迎注册","register");
            System.out.println(userInfo);
            /*
                INSERT INTO userinfo(username,password,nickname,age)
                VALUES('username','pwd','nickname',age);
             */
            String sql = "INSERT INTO userinfo(username,password,nickname,age)\n" +
                         "VALUES('"+userInfo.getUsername()+"','"+userInfo.getPassword()+"','"+userInfo.getNickname()+"',"+userInfo.getAge()+");";
            int num = statement.executeUpdate(sql);
            if (num>0)
                System.out.println("用户注册成功!");
            connection.close();
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
    }
}
